const router = require('express').Router()
const { ScreeningTimes, Order, Seat, Movie } = require('@/models')
const { data } = require('@/utils/send')
router.post('/', async (req, res) => {
    try {
        const order = await Order.create({ ...req.body, statu: 1 })
        if (!order) return res.cc('订单创建失败')
        const datas = data({ message: '订单创建成功' })
        res.send(datas)
        res.locals.data = datas
    } catch (error) {
        res.cc(error)
    }
})
router.get('/', async (req, res) => {
    try {
        const { user_id } = req.query
        const order = await Order.findAll({ where: { user_id } })
        const TimesId = order.map(item => item.event_id)
        const events = await Promise.all(TimesId.map(item => getTime(item)))
        const MovieId = events.map(item => item.movie_id)
        const movies = await Promise.all(MovieId.map(item => getMovie(item)))
        order.forEach((e, index) => {
            e.dataValues.event = events[index]
            e.dataValues.movie = movies[index]
        });
        if (!order) return res.cc('订单获取失败')
        const datas = data({ message: '订单获取成功', data: order })
        res.send(datas)
        res.locals.data = datas
    } catch (error) {
        res.cc(error)
    }
})
async function getTime(id) {
    return await ScreeningTimes.findOne({ where: { id } })
}
async function getMovie(id) {
    return await Movie.findOne({ where: { id } })
}
router.put('/', async (req, res) => {
    try {
        const { id, event_id, Selseat } = req.body
        const events = await getTime(event_id)
        const MovieId = events.movie_id
        const movies = await getMovie(MovieId)
        console.log(movies);
        const seat = await Seat.findOne({ where: { time_id: event_id } })
        let { seatinfo } = seat.dataValues
        seatinfo = upseat(seatinfo, Selseat)
        await Seat.update({ seatinfo }, { where: { time_id: event_id } })
        await Order.update({ statu: 2 }, { where: { id } })
        await Movie.update({ sales: movies.sales + 1 }, { where: { id: MovieId } })
        const datas = data({ message: '订单支付成功' })
        res.send(datas)
        // res.locals.data = datas
    } catch (error) {
        res.cc(error)
    }
})
router.delete('/', async (req, res) => {
    try {
        const { id } = req.query
        const order = await Order.update({ statu: 3 }, { where: { id } })
        if (!order) return res.cc('订单取消失败')
        const datas = data({ message: '订单取消成功' })
        res.send(datas)
        res.locals.data = datas
    } catch (error) {
        res.cc(error)
    }
})
function upseat(seatinfo, Selseat) {
    return seatinfo.map(seat => {
        if (Selseat.some(selectedSeat => seat.id === selectedSeat)) {
            seat.status = 2;
        }
        return seat;
    });
}
module.exports = router
